#include <stdint.h>
#include <stdio.h>
#include "fsm.h"

void func_s1_runing(EventID* x)
{
    printf("***********state 1 running***********\r\n");
}
void func_s2_runing(EventID* x)
{
    printf("***********state 2 running***********\r\n");
}
void func_s3_runing(EventID* x)
{
    printf("***********state 3 running***********\r\n");
}
void func_s1_Tr_12(EventID* x)
{
    printf("-----------func_s1_Tr_12-----------\r\n");
}
void func_s2_Tr_3(EventID* x)
{
    printf("-----------func_s2_Tr_3-----------\r\n");
}
void func_s3_Tr_s2(EventID* x)
{
    printf("-----------func_s3_Tr_s2-----------\r\n");
}
StateTransform stateTran[] =
{
    /*currState,event,  nextState,  func cycle,         func trigger */
    {state_1,   event_3,state_3,    func_s1_runing,     NULL},
    {state_2,   event_3,state_3,    func_s2_runing,     func_s2_Tr_3},
    {state_3,   event_1,state_2,    NULL,               func_s3_Tr_s2},
};
StateMachine_T stateMachine =
{
    .state = state_1,
    .transNum = sizeof(stateTran)/sizeof(stateTran[0]),
    .p_transform = stateTran
};


StateTransform* findTranss(StateMachine_T* pSM)
{
    int i;
    for (i = 0; i < pSM->transNum; i++)
    {
        if ((pSM->p_transform[i].curState == pSM->state))// && (pSM->p_transform[i].eventId == evt))
        {
            return &pSM->p_transform[i];
        }
    }
    return NULL;
}

void runStateMachine(StateMachine_T* pSM, EventID evt)
{
    StateTransform* pTrans;
    pTrans = findTranss(pSM);
    if (pTrans == NULL)
    {
        printf( "CurState= %d Do not process enent: %d\r\n", pSM->state,evt);
        return;
    }
    printf("curState = %d;",pTrans->curState);
    if(evt == pTrans->eventId)
    {
        printf("Event = %d\r\n",pTrans->eventId);
        if (pTrans->CBTrigFunc != NULL)
        {
            pTrans->CBTrigFunc(&evt);
        }
        else
        {
            printf("triger func is NULL\r\n");
        }
        pSM->state = pTrans->nextState;
    }
    else
    {
        if (pTrans->CBfunc != NULL)
        {
            pTrans->CBfunc(&evt);
        }
        else
        {
            printf("running func is NULL\r\n");
        }
    }
}

void main_fsm_run(int num)
{
    runStateMachine(&stateMachine, num);
}
